package com.yeqian.system.job;

import com.yeqian.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Slf4j
@DisallowConcurrentExecution
public class LogJob implements Job {

    @Value("${logging.file.path}")
    private String logPahth;


    /**
     * 定时清理日志 只保留一个月之内的文件
     *
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        File file = new File(logPahth);
        File[] files = file.listFiles();
        for (File childFile : files) {
            // 最后修改时间戳
            long lastModified = childFile.lastModified();
            if (DateUtils.isCurrent(lastModified, Calendar.MONTH, -1, false)) {
                childFile.delete();
                log.info("------------ " + childFile.getName() + " 删除成功------------");
            }
        }
        log.info("--------日志删除成功 " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " ------------");
    }
}
